<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert show-icon type="warning" title="注意:只允许为第三级分类设置相关参数" :closable="false"></el-alert>
      <el-row class="p-el-row">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader :options="getCateData" :props="cateDataProps" v-model="getKeys" @change="getKeysList" clearable></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="params_type" @tab-click="tabClick">
        <el-tab-pane name="many" label="动态参数">
          <el-button type="primary" :disabled="isDisabled" @click="isAddDialogVisible = true">动态参数</el-button>
          <el-table :data="many_list" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(item, i) in scope.row.attr_vals" closable @close="deleteAttrVals(i,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column width="200px">
              <template slot-scope="scope">
                <el-button type="primary" class="el-icon-edit" size="mini" @click="getAttrData(scope.row)">编辑</el-button>
                <el-button type="danger" class="el-icon-delete" size="mini" @click="changeAttr('delete', scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane name="only" label="静态属性">
          <el-button type="primary" :disabled="isDisabled" @click="isAddDialogVisible = true">静态属性</el-button>
          <el-table :data="only_list" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(item, i) in scope.row.attr_vals" closable @close="deleteAttrVals(i,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column width="200px">
              <template slot-scope="scope">
                <el-button type="primary" class="el-icon-edit" size="mini" @click="getAttrData(scope.row)">编辑</el-button>
                <el-button type="danger" class="el-icon-delete" size="mini" @click="changeAttr('delete', scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :title="'添加' + titleText" width="50%" @close="resetFormData" :close-on-click-modal="false" :visible.sync="isAddDialogVisible">
      <el-form :model="formData" label-width="80px" ref="addDataFormRef" :rules="addDataFormRules" >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="formData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
        <el-button @click="isAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changeAttr('add')">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改参数" :visible.sync="isEditDialogVisible" width="50%" @close="resetFormData('edit')" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" ref="editDataFormRef" :rules="editDataFormRules" >
        <el-form-item label="属性名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
        <span class="dialog-footer" slot="footer">
          <el-button @click="isEditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changeAttr('edit')">确认</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      getCateData: [],
      cateDataProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      getKeys: [],
      params_type: 'many',
      many_list: [],
      only_list: [],
      isAddDialogVisible: false,
      formData: {
        attr_name: ''
      },
      addDataFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      isEditDialogVisible: false,
      editForm: {
        attr_id: '',
        attr_name: ''
      },
      editDataFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if(res.meta.status !== 200) return this.$message({ type: 'error', message: '获取分类数据失败', duration: 2000 })
      this.getCateData = res.data
    },
    getKeysList() {
      if(this.getKeys.length !== 3) {
        this.getKeys = []
        return
      }
      this.getParamsData()
    },
    async getParamsData() {
      const { data: res } = await this.$http.get(`categories/${this.getId}/attributes`, { params: { sel: this.params_type } })
      if(res.meta.status !== 200) return this.$message({ type: 'error', message: '获取数据失败', duratopn: 2000 })
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals !== '' ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res)
      if(this.params_type === 'many') {
        this.many_list = res.data
      }else if(this.params_type === 'only') {
        this.only_list = res.data
      }
    },
    tabClick() {
      if(this.getKeys.length !== 3) return
      this.getParamsData()
    },
    resetFormData(type) {
      if(type === 'edit') {
        this.$refs.editDataFormRef.resetFields()
        return
      }
      this.$refs.addDataFormRef.resetFields()
    },
    async getAttrData(info) {
      this.isEditDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.getId}/attributes/${info.attr_id}`)
      this.editForm.attr_id = res.data.attr_id
      this.editForm.attr_name = res.data.attr_name
    },
    async changeAttr(type, info) {
      if(type === 'edit') {
        const { data: res } = await this.$http.put(`categories/${this.getId}/attributes/${this.editForm.attr_id}`, { attr_sel: this.params_type, attr_name: this.editForm.attr_name })
        if(res.meta.status !== 200) return this.$message({ type: 'error', message: '修改失败', duration: 2000 })
        this.getParamsData()
        this.isEditDialogVisible = false
      }else if(type === 'delete') {
        const flag = await this.$confirm('确定删除该参数吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(flag !== 'confirm') return
        const { data: res } = await this.$http.delete(`categories/${this.getId}/attributes/${info.attr_id}`)
        if(res.meta.status !== 200) return this.$message({ type: 'error', message: '删除失败', duration: 2000 })
        this.$message({ type: 'success', message: '删除成功', duration: 2000 })
        this.getParamsData()
        this.isAddDialogVisible = false
      }else if(type === 'add') {
        this.$refs.addDataFormRef.validate(async valid => {
          if(!valid) return this.$message({ type: 'error', message: '请填写正确的内容在尝试确认', duration: 2000 })
          const { data: res } = await this.$http.post(`categories/${this.getId}/attributes`, { attr_name: this.formData.attr_name, attr_sel: this.params_type })
          if(res.meta.status !== 201) return this.$message({ type: 'error', message: res.meta.msg, duration: 2000 })
          this.getParamsData()
          this.isAddDialogVisible = false
        })
      }
    },
    deleteAttrVals(index, info) {
      info.attr_vals.splice(index, 1)
      this.editAttrVals(info)
    },
    handleInputConfirm(info) {
      if(info.inputValue.trim().length !== 0) {
        info.attr_vals.push(info.inputValue.trim())
        this.editAttrVals(info)
      }
      info.inputValue = ''
      info.inputVisible = false
    },
    async editAttrVals(info) {
      const { data: res } = await this.$http.put(`categories/${this.getId}/attributes/${info.attr_id}`, { attr_name: info.attr_name, attr_sel: info.attr_sel, attr_vals: info.attr_vals.join(' ') })
      if(res.meta.status !== 200) return this.$message({ type: 'error', message: '添加参数失败', duration: 2000 })
      this.$message({ type: 'success', message: '修改参数项成功', duration: 2000 })
    },
    showInput(info) {
      info.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    isDisabled() {
      if(this.getKeys.length !== 3) {
        return true
      }
      return false
    },
    getId() {
      if(this.getKeys.length === 3) {
        return this.getKeys[2]
      }
      return null
    },
    titleText() {
      if(this.params_type === 'many') {
        return '动态参数'
      }else if(this.params_type === 'only') {
        return '静态属性'
      }
      return null
    }
  },
  watch: {
    getKeys(val) {
      if(val.length !== 3) {
        this.only_list = []
        this.many_list = []
      }
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style lang="less" scoped>
  .p-el-row{
    margin: 15px 0;
  }
  .el-cascader__dropdown{
    overflow-y: hidden;
  }
  .el-tag{
    margin: 5px;
  }
  .input-new-tag{
    width: 150px;
  }
</style>
